/**
 * 
 */
package vn.tecviets.thuandt.controller.action.login;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vn.tecviets.thuandt.model.bo.LoginBO;
import vn.tecviets.thuandt.model.form.LoginActionForm;

/*
 * LoginAction.java
 * 1.0
 * Mar 19, 2013 1:13:19 PM
 * 
 * Copyright notice
 *
 * Modification Logs:
 *
 * DATE					AUTHOR				DESCRIPTION
 * -----------------------------------------------------------
 * Mar 19, 2013			ThuanDT				Creation
 */

public class LoginAction extends Action {

	LoginBO loginBO = new LoginBO();

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		/*
		 * Check whether it is the first time the page is load or not
		 */
		if (request.getParameter("login") == null) {
			return mapping.findForward("login");
		}

		try {

			/*
			 * Get data of username and password
			 */
			LoginActionForm loginActionForm = (LoginActionForm) form;
			String username = loginActionForm.getUsername();
			String password = loginActionForm.getPassword();
			String role = loginBO.getUserRole(username, password);

			/*
			 * Check whether info of username and password are valid or not
			 */
			ActionErrors actionErrors = loginBO.validate(username, password, role);
			saveErrors(request, actionErrors);
			int actionErrorsSize = actionErrors.size();
			if (actionErrorsSize != 0) {
				return mapping.findForward("login");
			}

			/*
			 * Check role of user
			 */
			if ("Member".equals(role)) {
				return mapping.findForward("member");
			} else {
				return mapping.findForward("admin");
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}

	}

}
